﻿using Admin.Core.Common.Auth;
using Admin.Core.Common.Configs;
using Admin.Core.Common.Input;
using Admin.Core.Common.Output;
using Admin.Core.Common.ParamInput;
using Admin.Core.Model.Quality;
using Admin.Core.Repository.Quality;
using Admin.Core.Repository.Quality.CheckReport;
using Admin.Core.Service.Quality.Input;
using Admin.Core.Service.Quality.MachineCheck.Input;
using Admin.Core.Service.Quality.MachineCheck.Output;
using Admin.Core.Service.Quality.Output;
using Admin.Core.Service.TimingTask;
using AutoMapper;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.Quality
{
    public class MachineCheckService: IMachineCheckService
    {
        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly IMachineCheckRepository _machineCheckRepository;
        private readonly ICheckReportRepository _checkReportRepository;
        private readonly UploadConfig _uploadConfig;
        public MachineCheckService(IUser user, IMapper mapper, IMachineCheckRepository machineCheckRepository
            , IOptionsMonitor<UploadConfig> uploadConfig
          
            , ICheckReportRepository checkReportRepository)
        {
            _user = user;
            _mapper = mapper;
            _uploadConfig = uploadConfig.CurrentValue;
            _checkReportRepository = checkReportRepository;
            _machineCheckRepository = machineCheckRepository;
        }

        /// <summary>
        /// 获取物料类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetAsync(long id)
        {
            var result = await _machineCheckRepository.GetAsync<MachineCheckGetOutput>(id);
            return ResponseOutput.Ok(result);
        }

        public async Task<IResponseOutput> PageAsync(PageInput<MachineCheckFilterInput> input)
        {
            var key = input.Filter?.Name;
            var type = input.Filter?.Type;
            var status = input.Filter?.Status;
            var list = await _machineCheckRepository.baseRepository.Select
            .WhereIf(key.NotNull(), a => a.ControlNo.Contains(key))
            .WhereIf(type != null, a => a.CalType.Equals(type))
            .WhereIf(status != null, a => a.Status.Equals(status))
            .Count(out var total)
            .OrderBy(true, c => c.PlanCalTime)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(x => new MachineCheckListOutput
            {
                DepermentName = x.Deperment.Name,
                OwnerName = x.Owner.NickName,
                CalTypeName = x.CalType == 0 ? "内部校验" : "外部校验",
                CalCycle = x.CalNum.ToString() + (x.CalInterval == 1 ? "年":x.CalInterval == 2 ? "月" :"周"),
                PlanSupplierName = x.PlanSupplier.Name,
                Status = x.Status == -1 ? "正常" : x.Status == 0 ? "校验中" : x.Status == 1 ? "待确认" : x.Status == 2 ? "校验失败" : "",
            });
            //var projectList = _mapper.Map<List<MachineCheckListOutput>>(list);

            var data = new VxePageOutPut<MachineCheckListOutput>()
            {
                Result = list,
                Page = new VxePage { currentPage = input.CurrentPage, pageSize = input.PageSize, total = total, totalResult = total }
            };
            //var data = new PageOutput<MachineCheckListOutput>()
            //{
            //    List = list,
            //    Total = total
            //};
            return ResponseOutput.Ok(data);
        }

        /// <summary>
        /// 获取物料类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetCommitAsync(long id)
        {
            var entity = await _machineCheckRepository.baseRepository.Select.Where(x => x.Id == id)
                 .LeftJoin(a => a.CheckReports.AsSelect().Any(x => x.MachineCheckId == a.Id))
                .IncludeMany(a => a.CheckReports, then => then.Where(x => x.Status == 0))
                .ToOneAsync();
            if (entity.CheckReports.Count > 1 || entity.CheckReports.Count == 0)
            {
                return ResponseOutput.NotOk("校准报告数据状态异常，请联系技术人员处理");
            }
            var config = _uploadConfig.Calfile;
            var entityDto = _mapper.Map<CheckReportCommitGetOutput>(entity.CheckReports.FirstOrDefault());
            entityDto.Prefix = config.RequestPath+"/";
            entityDto.Rs = 1;
            return ResponseOutput.Ok(entityDto);
        }

        public async Task<IResponseOutput> GetOwnerPageAsync(PageInput<ConmonFilterInput> input)
        {
            var key = input.Filter?.Name;
            var list = await _machineCheckRepository.baseRepository.Select
            .WhereIf(key.NotNull(), a => a.ControlNo.Contains(key))
            .Where(x=>x.OwnerId==_user.Id)
            .Count(out var total)
            .OrderBy(true, c => c.PlanCalTime)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(x => new MachineCheckListOutput
            {
                DepermentName = x.Deperment.Name,
                OwnerName = x.Owner.NickName,
                CalTypeName = x.CalType == 0 ? "内部校验" : "外部校验",
                CalCycle = x.CalNum.ToString() + (x.CalInterval == 1 ? "年" : x.CalInterval == 2 ? "月": "周"),
                PlanSupplierName = x.PlanSupplier.Name,
                Status = x.Status == -1 ? "正常" : x.Status == 0 ? "校验中" : x.Status == 1 ? "待确认" : x.Status == 2 ? "校验失败" : "",
            });
            //var projectList = _mapper.Map<List<MachineCheckListOutput>>(list);

            var data = new VxePageOutPut<MachineCheckListOutput>()
            {
                Result = list,
                Page = new VxePage { currentPage = input.CurrentPage, pageSize = input.PageSize, total = total, totalResult = total }
            };
            //var data = new PageOutput<MachineCheckListOutput>()
            //{
            //    List = list,
            //    Total = total
            //};
            return ResponseOutput.Ok(data);
        }
        public async Task<IResponseOutput> GetCheckHisPageAsync(PageInput<ConmonFilterIdInput> input)
        {

            var key = input.Filter?.Id;
            var config = _uploadConfig.Calfile;

            var list = await _checkReportRepository.baseRepository.Select
            .WhereIf(key!=null, a => a.MachineCheckId.Equals(key))
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(x => new CheckHisOutput
            {
                CalUserName = x.CalUser.NickName,
                FilePath = config.RequestPath + "/" + x.FilePath,
                CalTime = x.ConfirmCalTime,
                Status = x.Status == 0? "待确认" : x.Status == 1 ? "检验成功" : x.Status == 2 ? "校验失败" :"",
            });
            var data = new VxePageOutPut<CheckHisOutput>()
            {
                Result = list,
                Page = new VxePage { currentPage = input.CurrentPage, pageSize = input.PageSize, total = total, totalResult = total }
            };

            return ResponseOutput.Ok(data);

        }
        
        public async Task<IResponseOutput> AddAsync(MachineCheckAddInput input)
        {
            var entity = _mapper.Map<MachineCheckEntity>(input);
            entity.Status = -1;
            entity.TenantId = _user.TenantId;
            var id = (await _machineCheckRepository.baseRepository.InsertAsync(entity)).Id;
            return ResponseOutput.Result(id > 0);
        }


        public async Task<IResponseOutput> UpdateAsync(MachineCheckUpdateInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }
            var entity = await _machineCheckRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("机台校验数据不存在！");
            }
            _mapper.Map(input, entity);
            await _machineCheckRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }
        public async Task<IResponseOutput> UpdateCommitAsync(CheckReportCommitInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }
            var entity = await _checkReportRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("机台报告数据不存在！");
            }
            var machineCheck = await _machineCheckRepository.GetAsync(input.MachineCheckId);
            _mapper.Map(input, entity);
            await _checkReportRepository.UpdateAsync(entity);

            if (entity.Status == 1)
            {
                machineCheck.Status = -1;

                if (machineCheck.CalInterval == 1)
                {
                    machineCheck.PlanCalTime = input.ConfirmCalTime.AddYears(machineCheck.CalNum).AddDays(-1);
                }
                else if (machineCheck.CalInterval == 2)
                {
                    machineCheck.PlanCalTime = input.ConfirmCalTime.AddMonths(machineCheck.CalNum).AddDays(-1);
                }
                else if (machineCheck.CalInterval == 3)
                {
                    machineCheck.PlanCalTime = input.ConfirmCalTime.AddDays(machineCheck.CalNum * 7);
                }
                await _machineCheckRepository.UpdateAsync(machineCheck);

            }
            else
            {
                machineCheck.Status = 2;
                await _machineCheckRepository.UpdateAsync(machineCheck);
            }

            return ResponseOutput.Ok();
        }

        

        public async Task<IResponseOutput> SoftDeleteAsync(long id)
        {
            var result = await _machineCheckRepository.SoftDeleteAsync(id);
            return ResponseOutput.Result(result);
        }
    }
}
